/*
 * Copyright (c) 2020-2021 imlzw@vip.qq.com jweb.cc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.jweb.adai.web.websocket.controller;

import cc.jweb.adai.web.websocket.service.LogWebSocketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint("/log.ws")
public class WebSocketController {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketController.class);

    @OnOpen
    public void onOpen(Session session) {
        LogWebSocketService.addSession(session);
        try {
            session.getBasicRemote().sendText("Web Socket 已经连接！");
        } catch (IOException e) {
            logger.error("Socket发送消息异常！", e);
        }
        logger.info("有新的WebSocket连接！{}", session.getId());
    }

    /**
     * 收到客户端消息时触发
     */
    @OnMessage
    public void onMessage(Session session, String key) throws IOException {
        session.getBasicRemote().sendText(key);//推送发送的消息
    }

    /**
     * 异常时触发
     */
    @OnError
    public void onError(Throwable throwable, Session session) {
        logger.error("WebSocket 异常！", throwable);
    }

    /**
     * 关闭连接时触发
     */
    @OnClose
    public void onClose(Session session) {
        LogWebSocketService.removeSession(session);
        logger.info("WebSocket 连接关闭了~~~~(>_<)~~~~");
    }


}